package cn.wangxl.group.rpc.netclient;

import cn.wangxl.group.rpc.discover.ServiceInfo;

import java.io.*;
import java.net.Socket;

/**
 * 网络客户端，BIO实现
 * @Deacription BioNetClient
 * @Author 20112128
 * @Date 2020/9/18 10:29
 **/
public class BioNetClient implements NetClient{

    @Override
    public byte[] sendRequest(byte[] data, ServiceInfo serviceInfo) {
        System.out.println("send rpc bio request");
        Socket socket = null;
        InputStream in = null;
        OutputStream out = null;
        byte[] content = new byte[4096];
        try{
            socket = new Socket(serviceInfo.getHost(),serviceInfo.getPort());
            out = socket.getOutputStream();
            out.write(data,0,data.length);

            in = socket.getInputStream();
            in.read(content);

        }catch(Exception e){
            e.printStackTrace();
            throw new RuntimeException("发送RPC请求失败");
        }finally {
            try {
                out.close();
                in.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return content;
    }
}
